<template>
  <div class="phasor-chart-container">
    <div ref="chartRef" class="phasor-chart"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'

const props = defineProps({
  faultResult: {
    type: Object,
    required: true,
    // 结构参考:
    // {
    //   fault_type: "单相接地故障",
    //   details: {
    //     phase_angles: { IA: 160, IB: 299, IC: 101 },
    //     phase_magnitudes: { IA: 0.37, IB: 1.02, IC: 0.77 }
    //   }
    // }
  },
})

const chartRef = ref(null)
let chartInstance = null

// 颜色映射
const colorMap = {
  A: '#ff4d4f', // 红
  B: '#52c41a', // 绿
  C: '#1890ff', // 蓝
}

// 绘制函数
const renderChart = () => {
  if (!props.faultResult?.details) return

  const { phase_angles, phase_magnitudes } = props.faultResult.details || {}
  if (!phase_angles || !phase_magnitudes) return

  if (!chartRef.value) return
  if (!chartInstance) chartInstance = echarts.init(chartRef.value)

  // 构造电流相量数据
  const seriesData = Object.keys(phase_angles).map((key) => {
    const angle = phase_angles[key]
    const mag = phase_magnitudes[key]
    const phase = key.slice(-1).toUpperCase()
    const color = colorMap[phase] || '#999'
    const theta = (angle / 180) * Math.PI // 转弧度
    return {
      name: key,
      value: [theta, mag],
      itemStyle: { color },
      symbol: 'arrow',
      symbolSize: 10,
    }
  })

  const option = {
    title: {
      text: props.faultResult.fault_type
        ? `相量图 - ${props.faultResult.fault_type}`
        : '电流相量图',
      left: 'center',
      textStyle: { fontSize: 16 },
    },
    polar: {},
    angleAxis: {
      type: 'value',
      startAngle: 90,
      min: 0,
      max: 360,
      clockwise: true,
      axisLabel: { formatter: (val) => `${val}°` },
    },
    radiusAxis: {
      min: 0,
      axisLabel: { formatter: (v) => v.toFixed(2) },
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const { name, value } = params.data
        const deg = ((value[0] * 180) / Math.PI).toFixed(2)
        const mag = value[1].toFixed(3)
        return `${name}<br>角度: ${deg}°<br>幅值: ${mag}`
      },
    },
    series: [
      {
        type: 'custom',
        coordinateSystem: 'polar',
        renderItem: (params, api) => {
          const theta = api.value(0)
          const r = api.value(1)
          const point = api.coord([theta, r])
          const color = api.style().fill
          return {
            type: 'path',
            shape: {
              pathData: 'M0,0 L0,-20 L5,-10 L-5,-10 Z', // 箭头
              x: point[0],
              y: point[1],
              width: 10,
              height: 20,
              rotation: -theta,
              scaleX: 1,
              scaleY: 1,
            },
            style: api.style({ fill: color }),
          }
        },
        data: seriesData,
        z: 10,
      },
    ],
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: Object.keys(phase_angles),
    },
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  renderChart()
  window.addEventListener('resize', () => chartInstance?.resize())
})

onBeforeUnmount(() => {
  chartInstance?.dispose()
  chartInstance = null
})

watch(() => props.faultResult, renderChart, { deep: true })
</script>

<style scoped>
.phasor-chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.phasor-chart {
  width: 100%;
  height: 400px;
}
</style>
